<script setup>
import { ref, onMounted } from 'vue'
import { getAdminLogs, addAdminLog, updateAdminLog, deleteAdminLog } from '@/api/admin'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'

const logs = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogLoading = ref(false)
const editDialogVisible = ref(false)
const editDialogLoading = ref(false)
const editingLog = ref(null)

const logForm = ref({
  action: '',
  description: '',
  ip_address: ''
})

const editForm = ref({
  action: '',
  description: '',
  ip_address: ''
})

const pagination = ref({
  page: 1,
  pageSize: 10,
  total: 0
})

const loadLogs = async () => {
  loading.value = true
  try {
    const response = await getAdminLogs({
      page: pagination.value.page,
      page_size: pagination.value.pageSize
    })
    logs.value = response.results || []
    pagination.value.total = response.count || 0
  } catch (error) {
    console.error(error)
    ElMessage.error('获取日志失败')
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page) => {
  pagination.value.page = page
  loadLogs()
}

const openAddDialog = () => {
  logForm.value = {
    action: '',
    description: '',
    ip_address: ''
  }
  dialogVisible.value = true
}

const submitLog = async () => {
  if (!logForm.value.action || !logForm.value.description) {
    ElMessage.error('请填写操作类型和描述')
    return
  }

  dialogLoading.value = true
  try {
    await addAdminLog(logForm.value)
    ElMessage.success('添加日志成功')
    dialogVisible.value = false
    loadLogs()
    updateChart()
  } catch (error) {
    console.error(error)
    ElMessage.error('添加日志失败')
  } finally {
    dialogLoading.value = false
  }
}

const openEditDialog = (log) => {
  editingLog.value = log
  editForm.value = {
    action: log.action,
    description: log.description,
    ip_address: log.ip_address || ''
  }
  editDialogVisible.value = true
}

const submitEditLog = async () => {
  if (!editForm.value.action || !editForm.value.description) {
    ElMessage.error('请填写操作类型和描述')
    return
  }

  editDialogLoading.value = true
  try {
    await updateAdminLog(editingLog.value.id, editForm.value)
    ElMessage.success('更新日志成功')
    editDialogVisible.value = false
    loadLogs()
    updateChart()
  } catch (error) {
    console.error(error)
    ElMessage.error('更新日志失败')
  } finally {
    editDialogLoading.value = false
  }
}

const handleDeleteLog = async (log) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除这条日志吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteAdminLog(log.id)
    ElMessage.success('删除日志成功')
    loadLogs()
    updateChart()
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error)
      ElMessage.error('删除日志失败')
    }
  }
}

const chartRef = ref(null)
let chart = null

const initChart = () => {
  if (!chartRef.value) return

  chart = echarts.init(chartRef.value)
  updateChart()
}

const updateChart = () => {
  if (!chart) return

  // 根据实际日志数据统计操作类型
  const actionStats = {}
  logs.value.forEach(log => {
    actionStats[log.action] = (actionStats[log.action] || 0) + 1
  })

  const chartData = Object.entries(actionStats).map(([name, value]) => ({
    name,
    value
  }))

  const option = {
    title: {
      text: '操作类型统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [{
      name: '操作类型',
      type: 'pie',
      radius: '50%',
      data: chartData.length > 0 ? chartData : [
        { value: 0, name: '暂无数据' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }

  chart.setOption(option)
}

onMounted(() => {
  loadLogs()
  initChart()
  window.addEventListener('resize', () => chart?.resize())
})
</script>

<template>
  <div class="admin-logs">
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <h2>管理员操作日志</h2>
              <el-button type="primary" @click="openAddDialog">添加日志</el-button>
            </div>
          </template>

          <el-table :data="logs" v-loading="loading" style="width: 100%">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="action" label="操作类型" />
            <el-table-column prop="description" label="描述" show-overflow-tooltip />
            <el-table-column prop="ip_address" label="IP地址" />
            <el-table-column prop="create_at" label="创建时间">
              <template #default="{ row }">
                {{ new Date(row.create_at).toLocaleString() }}
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :total="pagination.total"
            @current-change="handlePageChange"
            layout="total, prev, pager, next, jumper"
            style="margin-top: 20px; justify-content: center;"
          />
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card>
          <template #header>
            <h2>操作统计</h2>
          </template>
          <div ref="chartRef" style="width: 100%; height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加日志对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加操作日志"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="logForm" label-width="80px">
        <el-form-item label="操作类型" required>
          <el-select v-model="logForm.action" placeholder="请选择操作类型">
            <el-option label="新增" value="新增" />
            <el-option label="修改" value="修改" />
            <el-option label="删除" value="删除" />
            <el-option label="查询" value="查询" />
            <el-option label="登录" value="登录" />
            <el-option label="登出" value="登出" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" required>
          <el-input
            v-model="logForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入操作描述"
          />
        </el-form-item>
        <el-form-item label="IP地址">
          <el-input
            v-model="logForm.ip_address"
            placeholder="可选，留空将使用当前IP"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitLog" :loading="dialogLoading">
          确认添加
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.admin-logs {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

:deep(.el-table) {
  margin-bottom: 20px;
}

:deep(.el-pagination) {
  display: flex;
  justify-content: center;
}

@media screen and (max-width: 768px) {
  .admin-logs {
    padding: 10px;
  }

  .el-row {
    flex-direction: column;
  }

  .el-col {
    width: 100% !important;
    margin-bottom: 20px;
  }
}
</style>
